using System.Collections;
using System.IO;
using UnityEditor;
using UnityEngine;
using Framework.Define;
using Framework.Manager;
using System.Diagnostics;

using Debug = UnityEngine.Debug;

namespace FrameworkEditor.ApiGenerate
{
    public class ApiGenerate : EditorWindow
    {
        /// <summary>配置生成目录路径（即导表工具所在路径）</summary>
        private static string mApiGenerateFolderPath = string.Empty;
        /// <summary>配置生成Exe名称</summary>
        private static string mApiGenerateExeName = "ExcelToApi.exe";

        [MenuItem("FrameworkEditor/ApiGenerate")]
        public static void ApiGenerateEditor()
        {
            mApiGenerateFolderPath = ManagerCollection.DataManager.GetPlayerPrefs<string>(FrameworkDefine.ApiGenerateFolderPathKey);
            EditorWindow.GetWindowWithRect<ApiGenerate>(new Rect(0, 0, 500, 100), false, "ApiGenerate");
        }

        private void OnValidate()
        {
            mApiGenerateFolderPath = ManagerCollection.DataManager.GetPlayerPrefs<string>(FrameworkDefine.ApiGenerateFolderPathKey);
        }

        private void OnGUI()
        {
            GUIApiFolder();
            GUIApiGenerate();
        }

        private void GUIApiFolder()
        {
            GUILayout.Label("Api目录：" + mApiGenerateFolderPath);
            GUILayout.BeginHorizontal();
            if (GUILayout.Button("选择目录"))
            {
                string path = EditorUtility.OpenFolderPanel("选择目录", mApiGenerateFolderPath, "");
                if (!string.IsNullOrEmpty(path))
                {
                    mApiGenerateFolderPath = path + "/";
                    ManagerCollection.DataManager.SetPlayerPrefs<string>(FrameworkDefine.ApiGenerateFolderPathKey, mApiGenerateFolderPath);
                }
            }

            if (GUILayout.Button("打开目录"))
            {
                if (Directory.Exists(mApiGenerateFolderPath))
                    EditorUtility.RevealInFinder(mApiGenerateFolderPath);
                else
                    Debug.LogWarning("目录不存在");
            }

            if (GUILayout.Button("输出目录路径"))
            {
                Debug.Log("Api目录路径：" + mApiGenerateFolderPath);
            }
            GUILayout.EndHorizontal();
        }

        private void GUIApiGenerate()
        {
            GUILayout.Label("Api导出：");
            if (GUILayout.Button("Api导出"))
            {
                if (!Directory.Exists(mApiGenerateFolderPath))
                {
                    Debug.LogWarning("目录不存在");
                    return;
                }

                string exePath = mApiGenerateFolderPath + mApiGenerateExeName;
                if (!File.Exists(exePath))
                {
                    Debug.LogWarning("exe程序不存在，路径：" + exePath);
                    return;
                }

                ProcessStartInfo processStartInfo = new ProcessStartInfo();
                processStartInfo.FileName = exePath;
                processStartInfo.WorkingDirectory = mApiGenerateFolderPath;
                processStartInfo.UseShellExecute = false;
                processStartInfo.RedirectStandardOutput = true;

                using (Process process = Process.Start(processStartInfo))
                {
                    // 等待进程结束
                    process.WaitForExit();

                    string result = process.StandardOutput.ReadToEnd();
                    if (result.Contains("Api导出成功"))
                    {
                        Debug.Log(result);
                        CopyApiToFramework();
                    }
                    else
                    {
                        Debug.LogWarning(result);
                    }
                }
            }
        }

        private void CopyApiToFramework()
        {
            string sourcePath = string.Format("{0}Apis", mApiGenerateFolderPath);
            if (!Directory.Exists(sourcePath))
            {
                Debug.LogWarning("生成Api目录不存在，路径为：" + sourcePath);
                return;
            }

            string destPath = string.Format("{0}/{1}", Application.dataPath, FrameworkDefine.ApiRootDirectoryPath);
            if (Directory.Exists(destPath))
            {
                string[] files = Directory.GetFiles(destPath);
                if (files.Length > 0)
                    Directory.Delete(destPath, true);
            }
            else
            {
                Directory.CreateDirectory(destPath);
            }

            CopyDirectory(sourcePath, destPath);

            AssetDatabase.Refresh();
        }

        private void CopyDirectory(string pSourcePath, string pDestPath)
        {
            Debug.Log(string.Format("srcDirPath:{0} \n destDirPath:{1}", pSourcePath, pDestPath));

            if (!Directory.Exists(pDestPath))
                Directory.CreateDirectory(pDestPath);

            string[] directories = Directory.GetDirectories(pSourcePath);
            foreach (string sourcePath in directories)
            {
                string destPath = sourcePath.Replace(pSourcePath, pDestPath);
                CopyDirectory(sourcePath, destPath);
            }

            string[] files = Directory.GetFiles(pSourcePath);
            foreach (string file in files)
            {
                string destFile = file.Replace(pSourcePath, pDestPath);
                File.Copy(file, destFile, true);
            }
        }
    }
}